package com.wobito.common.filter;

import com.alibaba.fastjson.JSON;
import com.wobito.common.constants.ErrorCode;
import com.wobito.common.utils.JwtUtil;
import com.wobito.common.utils.ResultUtils;
import com.wobito.pojo.dto.user.AccessToken;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Component
@WebFilter(filterName = "TokenLoginFilter", urlPatterns = "/*")//先全部拦截
public class TokenLoginFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException, IOException {
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)) {
            filterChain.doFilter(request, response);
            return;
        }
        /**
         * swagger3 token 前面会加 Bearer
         * 进行过滤
         */
        String[] temp = authorization.split(" ");
        if (temp[0].equals("Bearer")) {
            authorization = temp[1];
        }
        AccessToken accessToken = JwtUtil.verifyTokenByRSA(authorization);
        //token错误报错
        if (Objects.isNull(accessToken)) {
            writeResp(ResultUtils.error(ErrorCode.NOT_LOGIN, "请重新登录"), response);
            return;
        }
        //token过期错误报错
        if (accessToken.getExp() < System.currentTimeMillis()) {
            writeResp(ResultUtils.error(ErrorCode.NOT_LOGIN, "token已过期"), response);
            return;
        }
        //已登录，获取用户信息，进行授权
        List<SimpleGrantedAuthority> authorities = accessToken.getAuthorities().stream().map(permission ->
                new SimpleGrantedAuthority(permission)
        ).collect(Collectors.toList());
        UsernamePasswordAuthenticationToken token =
                new UsernamePasswordAuthenticationToken(accessToken.getUsername(), null, authorities);
        SecurityContextHolder.getContext().setAuthentication(token);
        filterChain.doFilter(request, response);
    }

    public void writeResp(Object content, HttpServletResponse response) {
        response.setContentType("application/json;charset=utf-8");
        try {
            response.getWriter().write(JSON.toJSONString(content));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
